package com.osdp.common.listener;

import com.osdp.common.constant.CommonConstant;
import com.osdp.common.util.TokenHolder;
import org.apache.commons.lang3.StringUtils;


import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Cookie;
import java.util.Arrays;
import java.util.Optional;

/**
 * token放入本地线程
 */
public class TokenContextListener implements ServletRequestListener {
    /**
     * 获取token值，先从cookie中取，如无，则从headder 取
     * @param request HttpServletRequest
     * @return token
     */
    private String getToken(HttpServletRequest request){
        String token = request.getHeader(CommonConstant.HEADER_ACCESS_TOKEN);
        if(StringUtils.isEmpty(token)){
            Cookie[] cookies = request.getCookies();
            if(null == cookies || cookies.length == 0){
                token = null;
            }else {
                Optional<String> optional = Arrays.asList(cookies).stream().filter(e->
                        StringUtils.equals(CommonConstant.HEADER_ACCESS_TOKEN, e.getName()))
                        .map(c -> c.getValue()).findFirst();
                token = optional.isPresent()? optional.get(): null;
            }
        }
        return token;
    }
    @Override
    public void requestDestroyed(ServletRequestEvent requestEvent) {
        TokenHolder.removeToken();
    }

    @Override
    public void requestInitialized(ServletRequestEvent requestEvent) {
        if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
            throw new IllegalArgumentException(
                    "Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
        }
        HttpServletRequest request = (HttpServletRequest)requestEvent.getServletRequest();
        String token = getToken(request);
        TokenHolder.setToken(token);
    }

}
